<?php
declare(encoding='UTF-8');
error_reporting(-1);
require dirname(__FILE__) . '/../config.php';
require Config::ROOT . '/libs/FTP.php';
header('Content-Type: text/plain; charset=UTF-8');

$url = 'http://' . Config::DOMAIN_NAME . Config::WEB_DIR . '/';
$urls = array();
findUrls($url, $urls);
$urls = array_keys($urls);

checkSitemapFile();
writeSitemap($urls);

function writeSitemap(&$urls) {
    $file = fopen(Config::ROOT . '/sitemap.xml', 'w');
    fwrite($file, '<?xml version="1.0" encoding="UTF-8"?>' . "\n");
    fwrite($file, '<urlset' . "\n" .
'     xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n" .
'      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . "\n" .
'      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9' .
"\n" .
'            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' .
"\n");
    $date = date("Y-m-d");
    foreach ($urls as &$url) {
        fwrite($file, "<url>\n    <loc>$url</loc>\n" .
                "    <lastmod>$date</lastmod>\n</url>\n");
    }
    fwrite($file, '</urlset>');

    fclose($file);
}

function checkSitemapFile() {
    if (!file_exists(Config::ROOT . '/sitemap.xml')) {
        FTP::createFile('/sitemap.xml', 0666);
    }
    if (!is_writable(Config::ROOT . '/sitemap.xml')) {
        FTP::chmod('/sitemap.xml', 0666);
    }
}

function findUrls($url, &$urls, $level = 1) {
    if (!isset($urls[$url])) {
        echo "Adding page $url\n";
    }
    $urls[$url] = true;
    $page = @file_get_contents($url);
    if ($page === false) {
        return;
    }
    $doc = new DOMDocument();
    @$doc->loadHTML($page);
    $anchors = $doc->getElementsByTagName('a');
    foreach ($anchors as $anchor) {
        $nextUrl = resolveUrl($anchor->getAttribute('href'), $url);
        if (!isset($urls[$nextUrl])) {
            findUrls($nextUrl, $urls, $level + 1);
        }
    }
}

function resolveUrl($url, $ref) {
    if (substr($url, 0, 7) == 'http://') {
        return 'http://' . Config::DOMAIN_NAME . Config::WEB_DIR . '/';
    }
    if (substr($url, 0, 8) == 'https://') {
        return 'http://' . Config::DOMAIN_NAME . Config::WEB_DIR . '/';
    }
    if (substr($url, 0, 16) == '/utils/image.php') {
        return 'http://' . Config::DOMAIN_NAME . Config::WEB_DIR . '/';
    }
    if (substr($url, 0, 7) == '/event/') {
        return 'http://' . Config::DOMAIN_NAME . Config::WEB_DIR . '/';
    }
    if (substr($url, 0, 1) == '/') {
        return 'http://' . Config::DOMAIN_NAME . Config::WEB_DIR . $url;
    }
    return $ref . $url;
}
?>
